package com.qyhl.webtv.basiclib.utils.network.Other;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public abstract class HttpDownCallback implements Observer<ResponseBody> {
    public abstract void success(File file);

    public abstract void failure(int code, String err);

    public abstract void progress(long contentLength, long readLength, int percentage);

    private File file;
    private long length;
    private long nowlength;
    private int percentage;

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(ResponseBody responseBody) {
        length = responseBody.contentLength();
        nowlength = 0;
        percentage = -1;

        try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file))) {
            try (BufferedInputStream bufferedInputStream = new BufferedInputStream(responseBody.byteStream())) {
                byte[] bytes = new byte[1024 * 1024];
                int read;
                while ((read = bufferedInputStream.read(bytes)) != -1) {
                    bufferedOutputStream.write(bytes, 0, read);
                    update(read);
                }
                success(file);
            }
        } catch (IOException e) {
            failure(-2, "出错  " + e.toString());
        }
        responseBody.close();
    }

    private void update(int read) {
        nowlength += read;
        int v = (int) (100 * nowlength / (double) length);
        if (v > percentage) {
            percentage = v;
            progress(length, nowlength, percentage);
        }
    }

    @Override
    public void onError(Throwable e) {
        failure(-3, "出错  " + e.toString());
    }

    @Override
    public void onComplete() {

    }

    public void setFile(File file) {
        this.file = file;
    }
}
